package dev.spb3.mapper;

import dev.spb3.model.Order;
import dev.spb3.model.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper{
    /**
     * 查询所有用户
     * @return
     */
    @Select("SELECT * FROM users")
    List<User> getAllUsers();

    /**
     * 查询用户
     * @param id
     * @return
     */
    @Select("SELECT * FROM users WHERE id = #{id}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "registeredDate", column = "registered_date")
    })
    User getUserById(int id);
    /**
     * 添加用户
     * @param user
     * @return
     */
    @Insert("INSERT INTO users(username, email, registered_date) VALUES (#{username},#{email},#{registeredDate})")
    int insertUser(User user);

    /**
     * 更新用户
     * @param user
     * @return
     */
    @Update("UPDATE users SET username = #{username}, email=#{email} WHERE id = #{id}")
    int updateUser(User user);
    /**
     * 删除用户
     * @param id
     * @return
     */
    @Update("DELETE FROM users WHERE id = #{id}")
    int deleteUser(int id);

    @Select("SELECT * FROM users WHERE username=#{username} AND email=#{email}")
    User getUserByNameAndEmail(String username, String email);
    @Select("SELECT * FROM users WHERE username=#{username} AND email=#{email}")
    User getUserByMap(Map<String,Object>map);
    @Select("SELECT * FROM orders WHERE user_id = #{userId}")
    List<Order> getOrdersByUserId(int userId);
    @Select("SELECT * FROM users WHERE id = #{userId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "registeredDate", column = "registered_date"),
            @Result(property = "orders",javaType = List.class,
                    column = "id", many = @Many(select = "getOrdersByUserId"))
    })
    User getUserWithOrders(int userId);

    @Select("SELECT * FROM users WHERE id = #{userId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "registeredDate", column = "registered_date"),
            @Result(property = "orders",javaType = List.class,
                    column = "id", many = @Many(select = "getOrdersByUserId",
                    fetchType = FetchType.LAZY))
    })
    User getUserWithLazyOrders(int userId);
}
